package express

import (
	"OnlineRetailers/models"
	"fmt"
	"net/http"
	"regexp"
)

func getSession() (string, error) {

	url := models.GetSessionUrl

	//fmt.Println(url)

	req, err := http.NewRequest("GET", url, nil)
	req.Header.Set("Host", models.GetSessionHost)
	//Host: jwxt.hebic.cn
	req.Header.Set("User-Agent", " Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:97.0) Gecko/20100101 Firefox/97.0")
	//User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:97.0) Gecko/20100101 Firefox/97.0
	req.Header.Set("Referer", models.GetSessionUrl+"v4/Memberships.aspx")
	//Accept: application/json, text/javascript, */*; q=0.01
	req.Header.Set("Origin", models.GetSessionWeb)
	//Origin: http://jwxt.hebic.cn
	//Connection: keep-alive
	req.Header.Set("Connection", "keep-alive")
	//Referer: http://jwxt.hebic.cn/xsxk/zzxkyzb_cxZzxkYzbIndex.html?gnmkdm=N253512&layout=default&su=191305080930
	//Cookie: JSESSIONID=E57F810953C5B3DE049C2C47A9F294BF; SF_cookie_9=26458859
	client := &http.Client{}

	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(err)
		return "", err
	}

	name := resp.Header["Set-Cookie"]
	//fmt.Println(resp.Header)
	//fmt.Println(name[0])

	if len(name) == 0 {
		return "", fmt.Errorf("len(name)==0")
	}
	reg1 := regexp.MustCompile(`ASP.NET_SessionId=(?s:(.*?)); `)
	if reg1 == nil { //解释失败，返回nil
		fmt.Println("MustCompileErr")
		return "", fmt.Errorf("MustCompileErr")
	}

	result := reg1.FindAllStringSubmatch(name[0], 1)
	//fmt.Println(result)
	if len(result) == 0 {
		return "", fmt.Errorf("len(result)==0")
	}
	return result[0][1], nil
}
